package edu.zut.cn.handler.security;

import com.alibaba.fastjson.JSON;
import edu.zut.cn.domain.ResponseResult;
import edu.zut.cn.enums.CodeEnum;
import edu.zut.cn.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *  授权失败处理器
 *
 * @author 张小訫
 */
@Slf4j
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        accessDeniedException.printStackTrace();
        ResponseResult result = ResponseResult.fail(CodeEnum.NO_OPERATOR);
        log.info(CodeEnum.NO_OPERATOR.getMsg());
        //响应给前端
        WebUtils.renderString(response, JSON.toJSONString(result));
    }
}